package redisinit

import (
	"context"
	"fmt"
	"goods/goods"
	"strconv"
)

// 购物车添加
func CartCreate(cart map[string]interface{}) error {
	key := fmt.Sprintf("%d:%d", cart["UsersId"], cart["GoodsId"])

	return Rdb.HMSet(context.Background(), key, cart).Err()

}

// 购物车是否存在商品
func Exists(usersId, goodsId int64) bool {
	key := fmt.Sprintf("%d:%d", usersId, goodsId)

	return Rdb.Exists(context.Background(), key).Val() == 1

}

// 购物车修改数量
func CartSub(usersId, goodsId, num int64) error {
	key := fmt.Sprintf("%d:%d", usersId, goodsId)

	return Rdb.HGet(context.Background(), key, "num").Err()

	//return count
}

// 购物车查询商品
func CartInfo(usersId, goodsId int64) (cartInfo []*goods.CartList, err error) {
	key := fmt.Sprintf("%d:%d", usersId, goodsId)

	val := Rdb.HGetAll(context.Background(), key).Val()
	goods_id, _ := strconv.Atoi(val["GoodsId"])
	num, _ := strconv.Atoi(val["Num"])
	goods_price, _ := strconv.ParseFloat(val["GoodsPrice"], 64)
	goods_status, _ := strconv.Atoi(val["GoodsStatus"])
	cartInfo = append(cartInfo, &goods.CartList{
		GoodsId:     int64(goods_id),
		GoodsTitle:  val["GoodsTitle"],
		GoodsPrice:  float32(goods_price),
		GoodsStock:  int64(num),
		GoodsStatus: int64(goods_status),
	})
	return
	//return count
}

// 购物车删除
func CartDel(usersId, goodsId int64) error {
	key := fmt.Sprintf("%d:%d", usersId, goodsId)

	return Rdb.Del(context.Background(), key).Err()

	//return count
}

// 购物车清空
func CartClear(usersId int64) error {
	key := fmt.Sprintf("%d:*", usersId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		Rdb.Del(context.Background(), s)
	}
	return nil
	//return count
}
func CartAmount(usersId int64) (amount float64, count int) {
	key := fmt.Sprintf("%d:*", usersId)
	keys := Rdb.Keys(context.Background(), key).Val()
	for _, s := range keys {
		val := Rdb.HGetAll(context.Background(), s).Val()
		goods_price, _ := strconv.ParseFloat(val["GoodsPrice"], 64)
		num, _ := strconv.Atoi(val["Num"])
		//goods_status, _ := strconv.Atoi(val["GoodsStatus"])
		if val["GoodsStatus"] == "1" {
			count += num
			amount += goods_price * float64(num)
		}
	}
	return
}
